import { EcsSystem, filter, NodeComponent } from "db://pkg/@gamex/cc-ecs";
import { AutoMoveComponent } from "../component/AutoMoveComponent";
import { Vec3 } from "cc";
import { PropComponent } from "../component/PropComponent";
import { gameRange } from "../../../Common";

export class AutoMoveSystem extends EcsSystem {
    private filter = filter.all(AutoMoveComponent, NodeComponent);

    protected execute(dt?: number, ...args: any[]): void {
        this.query(this.filter).forEach(entity => {
            this.run(entity.getComponent(AutoMoveComponent), dt)
        })
    }

    private run(moveComp: AutoMoveComponent, dt: number) {
        if (!moveComp.toward.length) return;
        const distanceVec = Vec3.multiplyScalar(new Vec3(), moveComp.toward.normalize(), moveComp.speed * dt);
        
        moveComp.entity.getComponent(NodeComponent).addPosition(distanceVec.x, distanceVec.y, distanceVec.z);
        // 如果是道具 移动到左右边界后向反向移动
        if (moveComp.entity.has(PropComponent)) {
            if (moveComp.entity.getComponent(NodeComponent).x < gameRange.minX + 1 || moveComp.entity.getComponent(NodeComponent).x > gameRange.maxX - 1) {
                moveComp.toward = new Vec3(-moveComp.toward.x, moveComp.toward.y, moveComp.toward.z);
            }
        }
    }
}